package com.freesun.shop.service.impl;


import cn.hutool.extra.emoji.EmojiUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.entity.User;
import com.freesun.shop.mapper.UserMapper;
import com.freesun.shop.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Override
    public User findUserByUsername(String openid) {
        Assert.notNull(openid,"用户的ID不能为Null");
        logger.info("通过用户的openID：{},查询该用户",openid);
        User user = this.baseMapper.selectById(openid);

        return user;
    }

    @Override
    public User regeister(String openid) {
        logger.info("注册新用户:{}",openid);
        User user = new User();
        user.setUserId(openid);
        user.setModifyTime(LocalDateTime.now());
        user.setUserRegtime(LocalDateTime.now());
        user.setUserRegip("127.0.0.1");
        this.baseMapper.insert(user);
        logger.info("注册用户成功");
        return user;
    }

    @Override
    public void updateUserLoginRec(User user) {
        Assert.notNull(user,"更新用户时,用户不能为Null");
        User userDb = this.baseMapper.selectById(user.getUserId());
        userDb.setUserLastip("127.0.0.1");
        userDb.setUserLasttime(LocalDateTime.now());
        this.baseMapper.updateById(userDb);
    }

    @Override
    public void updateUser(String userId, String nickName, String pic) {
        Assert.notNull(userId, "用户的ID不能为Null");
        User user = this.baseMapper.selectById(userId);
        if (null == user) {
            throw new RuntimeException("不合法的用户");
        }
        //若用户名使用表情做头像,时无法保存到数据库里面的
        String alias = EmojiUtil.toAlias(nickName);
        user.setNickName(alias);
        user.setPic(pic);
        user.setModifyTime(LocalDateTime.now());
        this.baseMapper.updateById(user);
    }

    public static void main(String[] args) {
        String alias = EmojiUtil.toAlias("我是恶魔之眼\uD83D\uDC41");
        System.out.println("alias = " + alias);
        String unicode = EmojiUtil.toUnicode(alias);
        System.out.println("unicode = " + unicode);
    }
}
